'''
如E贝贝（尊享版）少儿保险产品计划
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from common.helper import Helper
from urllib.parse import urlencode
import requests


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "如E贝贝（尊享版）少儿保险产品计划"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(3, 11)],
            # 性别
            "gender": ["M", "F"],
            # 保障期限
            "interval": ["3", "5", "10"],
            # 购买份数
            "count": ["1", "2", "3"]

        }

        for v in product(plan["year"], plan["gender"], plan["interval"], plan["count"]):
            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3]
            ))

    # 执行爬虫
    def requestJson(self, dt=None):


        data = {

            "geNoCarTemporary.recommendedType": "",
            "geNoCarTemporary.referralCode": "",
            "geNoCarTemporary.transactionCodeType": "",
            "geNoCarTemporary.quoteMain.quoteNo": "",
            "geNoCarTemporary.quoteMain.eid": "G220171109110448089",
            "geNoCarTemporary.quoteMain.hxssProposalNo": "",
            "geNoCarTemporary.quoteMain.riskCode": "",
            "geNoCarTemporary.quoteMain.classCode": "",
            "geNoCarTemporary.quoteMain.businessNature": "8",
            "geNoCarTemporary.quoteMain.areaCodePro": "",
            "geNoCarTemporary.quoteMain.areaCode": "",
            "geNoCarTemporary.quoteMain.leaveSegment": "",
            "geNoCarTemporary.quoteMain.leaveWay": "",
            "geNoCarTemporary.quoteMain.userID": "",
            "geNoCarTemporary.quoteMain.userType": "01",
            "geNoCarTemporary.quoteMain.channelCode": "",
            "geNoCarTemporary.quoteMain.renewalFlag": "",
            "geNoCarTemporary.quoteMain.oldlPolicyNo": "",
            "geNoCarTemporary.quoteMain.currency": "RMB",
            "geNoCarTemporary.quoteMain.sumDiscount": "0",
            "geNoCarTemporary.quoteMain.sumPremium": "1060",
            "geNoCarTemporary.quoteMain.sumDiscountPremium": "1060",
            "geNoCarTemporary.quoteMain.sumBasePremiun": "0",
            "geNoCarTemporary.quoteMain.inputDate": "2012 - 02 - 14",
            "geNoCarTemporary.quoteMain.period": "30",
            "geNoCarTemporary.quoteMain.insuYearFlag": "A",
            "geNoCarTemporary.quoteMain.invalidDate": "2012 - 02 - 02",
            "geNoCarTemporary.quoteMain.quoteStatus": "01",
            "geNoCarTemporary.quoteMain.businessArea": "2",
            "geNoCarTemporary.quoteMain.createDate": "2012 - 02 - 14",
            "geNoCarTemporary.quoteMain.updateDate": "2012 - 02 - 14",
            "geNoCarTemporary.quoteMain.agentCode": "",
            "geNoCarTemporary.quoteMain.agentName": "",
            "geNoCarTemporary.quoteMain.departmentNo": "",
            "geNoCarTemporary.quoteMain.departmentName": "",
            "geNoCarTemporary.quoteMain.flag": "",
            "geNoCarTemporary.quoteMain.copies": dt["count"],
            "geNoCarTemporary.quoteMain.productName": "",
            "geNoCarTemporary.geQuoteNocarDutys[0].riskCode": "REBBZXB",
            "geNoCarTemporary.geQuoteNocarDutys[0].dutycode": "326",
            "geNoCarTemporary.geQuoteNocarDutys[0].dutydesc": "18周岁前：附加合同所交保险费（不计利息）与附加合同现金价值的较大者；18周岁后：附加合同所交保险费（不计利息）",
            "geNoCarTemporary.geQuoteNocarDutys[0].premium": "4170.00",
            "geNoCarTemporary.geQuoteNocarDutys[0].amountDesc": "",
            "geNoCarTemporary.geQuoteNocarDutys[0].formerPremium": "1520.00",
            "geNoCarTemporary.geQuoteNocarDutys[1].riskCode": "REBBZXB",
            "geNoCarTemporary.geQuoteNocarDutys[1].dutycode": "570",
            "geNoCarTemporary.geQuoteNocarDutys[1].dutydesc": "18周岁前：主险合同所交保费；18周岁后180天内因疾病：主险合同所交保费；18周岁后其他原因：160 % 主险合同所交保费",
            "geNoCarTemporary.geQuoteNocarDutys[1].premium": "3900.00",
            "geNoCarTemporary.geQuoteNocarDutys[1].amountDesc": "",
            "geNoCarTemporary.geQuoteNocarDutys[1].formerPremium": "3900.00",
            "geNoCarTemporary.geQuoteNocarExtra.quoteNo": "",
            "geNoCarTemporary.geQuoteNocarExtra.portTarget": "",
            "geNoCarTemporary.geQuoteNocarExtra.portEndPointer": "",
            "geNoCarTemporary.productCode": "1016",
            "geNoCarTemporary.proposalSID": "",
            "geNoCarTemporary.isExsitBnf": "",
            "geNoCarTemporary.insuranceType": "0",
            "geNoCarTemporary.areaCodeProDesc": "",
            "geNoCarTemporary.areaCodeDesc": "",
            "geNoCarTemporary.insuYearFlagDesc": "",
            "geNoCarTemporary.portEndPointerDesc": "",
            "geNoCarTemporary.existDiscountFlag": "false",
            "geNoCarTemporary.discountID": "",
            "geNoCarTemporary.topImg": "",
            "geNoCarTemporary.rightImg": "",
            "geNoCarTemporary.existLuckDrawFlag": "false",
            "geNoCarTemporary.moreBuyProposalSID": "",
            "geNoCarTemporary.moreBuyFlag": "0",
            "geNoCarTemporary.lotteryPic1": "",
            "geNoCarTemporary.lotteryPic2": "",
            "geNoCarTemporary.insuredSex": "1" if dt["gender"] == "M" else "2",
            "geNoCarTemporary.insuredBirthday": "{year}-01-01".format( year = str(2019-int(dt["year"]))),
            "geNoCarTemporary.pupillus": "0",
            "geNoCarTemporary.insuredCount": dt["count"],
            "geNoCarTemporary.payType": dt["interval"] + "Y",
        }

        payload = urlencode(data).replace("+", "")

        try:
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and r.text != "false":


                price = Helper.decimalParse( r.json()["quoteMain"]["sumPremium"] )

                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }

                self.mysql.updatePrice( data )

            else:

                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "state":3
                }
                self.mysql.updateTask( data )
                print("/*产品价格更新失败:%s*/"%dt["id"])
        except :

            pass


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson( dt )
